/**
 * Created by zengyx on 16/12/16.
 */
import store from '@/store/index.js'
import m7dicMap from '@/utils/m7dicMap'
import xss from 'xss'
import CryptoJS from "crypto-js"
let crypto = require('crypto')
// xss处理
// 设置白名单
let whiteList = xss.getDefaultWhiteList() // 获取默认白名单
// 添加新的白名单标签或属性
for (let i in whiteList) {
  whiteList[i].push('style', 'class')
  if (i === 'table') {
    whiteList[i].push('cellpadding', 'cellspacing', 'bordercolor')
  }
}
whiteList.strike = ['style', 'class']
whiteList.label7moor = []
// whiteList.style = ['type']
let options = {
  whiteList,
  css: false,
  stripIgnoreTag: true, // 非白名单标签，过滤标签，显示标签里的内容
  stripIgnoreTagBody: ['script', 'style']
}
let optionsAttr = {
  whiteList,
  css: false,
  stripIgnoreTag: true, // 非白名单标签，过滤标签，显示标签里的内容
  stripIgnoreTagBody: ['script', 'style'],
  onTagAttr: function (tag, attr, value) {        // 上传的属性出现特殊值，做特殊处理
    var indexNum = value.indexOf('data:image')
    if (tag==='img' && attr==='src' && indexNum===0) {
      return attr + '="'+ value +'"'
    }
  }
}
let myxss = new xss.FilterXSS(options)
let attrXss = new xss.FilterXSS(optionsAttr)
export function filterXSS (content, flag) {
  if (flag) {
    return attrXss.process(content)
  } else {
    return myxss.process(content)
  }
}
// 客户导入批次号生成
export function getDateNo () {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let str = year + '' + (month > 9 ? month : '0' + month) + '' + (day > 9 ? day : '0' + day)
  let h = date.getHours()
  let m = date.getMinutes()
  let s = date.getSeconds()
  str += (h > 9 ? h : '0' + h) + '' + (m > 9 ? m : '0' + m) + '' + (s > 9 ? s : '0' + s)
  return str
}
export function phoneFilterChats (phoneNumber) {
  if (!phoneNumber) return phoneNumber
  // 需要过滤的字符
  let filterArr = [8237, 8236]
  // 过滤后的电话号码
  return phoneNumber
    .trim()
    .split('')
    .filter(val => {
      return filterArr.indexOf(val.codePointAt()) === -1
    })
    .join('')
}

export function copy (targetObj) {
  targetObj = targetObj || {}
  let tempObj = {}
  for (let key in targetObj) {
    tempObj[key] = targetObj[key]
  }
  return tempObj
}
/**
 * 去掉字符串中所有“-”中划线
 * @param str
 * @returns {string}
 */
export function strLineAll (str) {
  let result
  result = str.replace(/(^-+)|(-+$)/g, '')
  result = result.replace(/-/g, '')
  return result
}
export function deepClone (targetObj) {
  let tempObj
  if (typeof targetObj === 'object') {
    if (targetObj === null) {
      tempObj = null
    } else {
      if (targetObj instanceof Date) {
        tempObj = targetObj
      } else if (targetObj instanceof Array) {
        tempObj = []
        for (let i = 0, len = targetObj.length; i < len; i++) {
          tempObj.push(deepClone(targetObj[i]))
        }
      } else {
        tempObj = {}
        for (let j in targetObj) {
          tempObj[j] = deepClone(targetObj[j])
        }
      }
    }
  } else {
    tempObj = targetObj
  }
  return tempObj
}

// 对象合并
export function utilExtend (target, source) {
  if (source === null || typeof source !== 'object') return target
  let keys = Object.keys(source)
  let i = keys.length
  while (i--) {
    target[keys[i]] = source[keys[i]]
  }

  return target
}

export const Base64 = {
    // private property
  _keyStr: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',

  encode: input => {
    let output = ''
    let chr1, chr2, chr3, enc1, enc2, enc3, enc4
    let i = 0
    input = Base64._utf8_encode(input)
    while (i < input.length) {
      chr1 = input.charCodeAt(i++)
      chr2 = input.charCodeAt(i++)
      chr3 = input.charCodeAt(i++)
      enc1 = chr1 >> 2
      enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
      enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
      enc4 = chr3 & 63
      if (isNaN(chr2)) {
        enc3 = enc4 = 64
      } else if (isNaN(chr3)) {
        enc4 = 64
      }
      output = output +
        Base64._keyStr.charAt(enc1) + Base64._keyStr.charAt(enc2) +
        Base64._keyStr.charAt(enc3) + Base64._keyStr.charAt(enc4)
    }
    return output
  },

// public method for decoding
  decode: input => {
    let output = ''
    let chr1, chr2, chr3
    let enc1, enc2, enc3, enc4
    let i = 0
    // todo []中括号里面使用转移符是多余的
    // input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '')
    input = input.replace(/[^A-Za-z0-9\u002b\u002f\u003d]/g, '')
    while (i < input.length) {
      enc1 = Base64._keyStr.indexOf(input.charAt(i++))
      enc2 = Base64._keyStr.indexOf(input.charAt(i++))
      enc3 = Base64._keyStr.indexOf(input.charAt(i++))
      enc4 = Base64._keyStr.indexOf(input.charAt(i++))
      chr1 = (enc1 << 2) | (enc2 >> 4)
      chr2 = ((enc2 & 15) << 4) | (enc3 >> 2)
      chr3 = ((enc3 & 3) << 6) | enc4
      output = output + String.fromCharCode(chr1)
      if (enc3 !== 64) {
        output = output + String.fromCharCode(chr2)
      }
      if (enc4 !== 64) {
        output = output + String.fromCharCode(chr3)
      }
    }
    output = Base64._utf8_decode(output)
    return output
  },

  _utf8_encode: string => {
    string = string.replace(/\r\n/g, '\n')
    let utftext = ''
    for (let n = 0; n < string.length; n++) {
      let c = string.charCodeAt(n)
      if (c < 128) {
        utftext += String.fromCharCode(c)
      } else if ((c > 127) && (c < 2048)) {
        utftext += String.fromCharCode((c >> 6) | 192)
        utftext += String.fromCharCode((c & 63) | 128)
      } else {
        utftext += String.fromCharCode((c >> 12) | 224)
        utftext += String.fromCharCode(((c >> 6) & 63) | 128)
        utftext += String.fromCharCode((c & 63) | 128)
      }
    }
    return utftext
  },

  _utf8_decode: utftext => {
    let string = ''
    let i = 0
    let [c, c2, c3] = [0, 0, 0]
    while (i < utftext.length) {
      c = utftext.charCodeAt(i)
      if (c < 128) {
        string += String.fromCharCode(c)
        i++
      } else if ((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i + 1)
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63))
        i += 2
      } else {
        c2 = utftext.charCodeAt(i + 1)
        c3 = utftext.charCodeAt(i + 2)
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63))
        i += 3
      }
    }
    return string
  }
}
// 用于timeFormat 下的language方法
export function timeFormatM7Language (info, params, returnNull) {
  // returnNull 用来通过中文做key来匹配英文，若是没有匹配到直接return ""
  let local = window.langJson || {}
  let arr = []
  let language = ''
  if (typeof info === 'string') {
    arr = info.split('.')
    if (arr.length === 1) {
      language = local['message'][arr[0]] ? local['message'][arr[0]] : info
    } else if (arr.length === 2) {
      if (local[arr[0]] && local[arr[0]][arr[1]]) {
        language = local[arr[0]][arr[1]]
      } else {
        if (!returnNull) {
          language = info
        }
      }
    } else if (arr.length === 3) {
      if (local[arr[0]] && local[arr[0]][arr[1]] && local[arr[0]][arr[1]][arr[2]]) {
        language = local[arr[0]][arr[1]][arr[2]]
      } else {
        if (!returnNull) {
          language = info
        }
      }
    } else {
      if (!returnNull) {
        language = info
      }
    }
  } else {
    language = local['message']['unknown_err']
  }
  if (params) {
    for (let key in params) {
      let reg = new RegExp(`{${key}}`, 'g')
      language = language.replace(reg, params[key])
    }
  }

  return language
}
export function m7Language (info, params, returnNull) {
  // returnNull 用来通过中文做key来匹配英文，若是没有匹配到直接return ""
  let local = window.langJson || {}
  let arr = []
  let language = ''
  if (typeof info === 'string') {
    arr = info.split('.')
    if (arr.length === 1) {
      language = local['message'][arr[0]] ? local['message'][arr[0]] : info
    } else if (arr.length === 2) {
      if (local[arr[0]] && local[arr[0]][arr[1]]) {
        language = local[arr[0]][arr[1]]
      } else {
        if (!returnNull) {
          language = info
        }
      }
    } else if (arr.length === 3) {
      if (local[arr[0]] && local[arr[0]][arr[1]] && local[arr[0]][arr[1]][arr[2]]) {
        language = local[arr[0]][arr[1]][arr[2]]
      } else {
        if (!returnNull) {
          language = info
        }
      }
    } else {
      if (!returnNull) {
        language = info
      }
    }
  } else {
    language = local['message']['unknown_err']
  }
  if (params) {
    for (let key in params) {
      let reg = new RegExp(`{${key}}`, 'g')
      language = language.replace(reg, params[key])
    }
  }

  return language
}
export function getCache (type, id, node, callBack) {
  if (!type) {
    return []
  }
  var cache = []
  var typeData = m7dicMap.getCache(type)
  // if (store.state.session.dicMap[type]) {
  //   cache = store.state.session.dicMap[type]
  if (type === 'agents') {
    cache = m7dicMap.getCache('agentObj')
    if (id) {
      if (callBack) {
        callBack(copy(cache[id]))
        return
      } else {
        return copy(cache[id])
      }
    } else {
      if (callBack) {
        callBack(cache)
        return
      }
    }
  }
  if (typeData) {
    cache = typeData
    if (id) {
      for (var i = 0; i < cache.length; i++) {
        if (cache[i]._id === id) {
          if (type === 'accountPbx' && callBack) {
            callBack(copy(cache[i]))
            return
          } else {
            return copy(cache[i])
          }
        }
      }
      if (type === 'accountPbx' && callBack) { // 解决迁移pbx之后，找不到pbx,重新请求全部的pbx存在异步导致代码冗余
        node.$store.dispatch('getCache', {type: 'pbx', id: id}).then(resp => {
          callBack(resp)
          return
        })
      } else {
        return null
      }
    } else { // 预防dispatch异步之后2个callBack
      if (type === 'accountPbx' && callBack) {
        callBack(cache)
        return
      }
    }
    if (type !== 'accountPbx') {
      return cache
    }
  }
}
export function matchingOperator (obj) {
  var sub3 = obj.substr(0, 3)
  var sub4 = obj.substr(0, 4)
  let ydsmsChannel = ['134', '135', '136', '137', '138', '139', '150', '151', '152', '157', '158', '159', '182', '183', '184', '187', '178', '188', '147', '1705']
  let ltsmsChannel = ['130', '131', '132', '145', '155', '156', '176', '185', '186', '1709']
  let dxsmsChannel = ['133', '153', '177', '180', '181', '189', '1349', '1700']

  if (ydsmsChannel.indexOf(sub3) !== -1 || ydsmsChannel.indexOf(sub4) !== -1) {
    return 'yd_smsChannel'
  } else if (dxsmsChannel.indexOf(sub3) !== -1 || dxsmsChannel.indexOf(sub4) !== -1) {
    return 'dx_smsChannel'
  } else if (ltsmsChannel.indexOf(sub3) !== -1 || ltsmsChannel.indexOf(sub4) !== -1) {
    return 'lt_smsChannel'
  } else {
    return 'def_smsChannel'
  }
}
export function getCacheByCodeValue (type, value) {
  type = type || ''
  // var cache = store.state.session.dicMap[type] || []
  var cache = m7dicMap.getCache(type) || []
  if (value) {
    for (var i = 0; i < cache.length; i++) {
      if (cache[i].code_value === value) {
        return copy(cache[i])
      }
    }
    return null
  }
  return cache
}

export function getCacheByKey (type, key, value) {
  type = type || ''
  // var cache = store.state.session.dicMap[type] || []
  var cache = m7dicMap.getCache(type) || []
  for (var i = 0; i < cache.length; i++) {
    var cacheItem = cache[i]
    if (cacheItem[key] === value) {
      return cacheItem
    }
  }
  return null
}

// 解决邮件卡片找不到座席技能组的情况，目前只用于邮件卡片，这个方法存在dicmap内取不到数据的情况，如果遇到的话采用这个方法避免
export function getEmailQueueCacheByKey (type, key, value) {
  type = type || ''
  // var cache = store.state.session.dicMap[type]
  var cache = m7dicMap.getCache(type)
  if (!cache) {
    store.dispatch('getCache', {type: type}).then((resp) => {
      if (resp) {
        cache = resp
        for (var i = 0; i < cache.length; i++) {
          var cacheItem = cache[i]
          if (cacheItem[key] === value) {
            return cacheItem
          }
        }
      }
    })
  } else {
    for (var i = 0; i < cache.length; i++) {
      var cacheItem = cache[i]
      if (cacheItem[key] === value) {
        return cacheItem
      }
    }
  }
  return null
}
export function getDicCacheName (type, value) {
  type = type || ''
  value = value || ''
  // var dic = store.state.session.dicMap[type] || []
  var dic = m7dicMap.getCache(type) || []
  for (var i = 0; i < dic.length; i++) {
    if (dic[i].code_value === value) {
      return dic[i].code_name
    }
  }
  return value
}
/**
 * (86401, true) -->  1天0小时0分1秒
 * (86401, false) -->  24:00:01
 */
export function getCallTimeLength (second, format) {
  if (second) {
    let d
    let h
    let m
    let s
    if (second === null || second < 0) {
      return
    }
    d = Math.floor(second / (24 * 3600 * 1000))
    h = second / 3600 | 0
    second = parseFloat(second) - h * 3600
    if (parseInt(h) < 10) {
      h = '0' + h
    }
    m = second / 60 | 0
    s = (parseFloat(second) - m * 60).toFixed(0)
    if (parseInt(m) < 10) {
      m = '0' + m
    }
    if (s < 10) {
      s = '0' + s
    }
    if (format) {
      let time
      if (d > 0) {
        time += d + m7Language('public.day2')
      }
      if (h > 0) {
        time += h + m7Language('public.hours2')
      }
      if (m > 0) {
        time += m + m7Language('public.minutes2')
      }
      if (s > 0) {
        time += s + m7Language('public.seconds')
      }
      return time
    } else {
      return h + ':' + m + ':' + s
    }
  } else {
    return '00:00:00'
  }
}
export function dateParse (date) {
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate()
  let str = year + '-' + (month > 9 ? month : '0' + month) + '-' + (day > 9 ? day : '0' + day)
  return str
}
export function formatShortTime (date) {
  if (!date) {
    return {time: '', name: ''}
  }

  let currentLang = window.localStorage.getItem('lang') || 'zh_CN'
  let _d = date.substring(0, 10)
  let _t = date.substring(11, 16)
  let a = _d.split('-')
  let dd = parseInt(a[0], 10) + '/' + parseInt(a[1], 10) + '/' + parseInt(a[2], 10)
  let today = new Date()
  let now = countDay(0)
  let yesterday = countDay(-1)
  let _yesterday = countDay(-2)
  let result = {}
  result.time = date
  result.name = _d
  if (dd === now) {
    result.name = _t
  } else if (dd === yesterday) {
    if (currentLang !== 'zh_CN') { // 只要不是中文就展示日期（此处无需做国际化）
      result.name = _d
    } else {
      result.name = '昨天' + _t
    }
  } else if (dd === _yesterday) {
    if (currentLang !== 'zh_CN') {
      result.name = _d
    } else {
      result.name = '前天' + _t
    }
  } else if (a[0] < today.getFullYear()) {
    result.name = _d
  } else if (Date.parse(dd) < Date.parse(now)) {
    result.name = a[1] + '-' + a[2]
  }
  return result
}
/**
 * 2017-2-17 16:40:40 -->  2017-2-17
 * 2017-2-17 16:40:40 -->  16:40
 * @param dateTimeStr
 * @returns {string}
 */
export function getDateTimeByStr (dateTimeStr, type) {
  if (!dateTimeStr || !type) {
    return ''
  }
  let result = ''
  let datetime = dateTimeStr.split(' ')
  if (type === 'date') {
    result = datetime[0].substring(0, 11)
  } else if (type === 'time') {
    result = datetime[1].substring(0, 5)
  }
  return result
}

/**
 * 规范时间差
 */
export function formatTimestamp (timelength) {
  var formatTime = ''
  var day = Math.floor(timelength / (24 * 3600 * 1000))
  var restTime = timelength % (24 * 3600 * 1000)
  var hour = 0
  var minutes = 0
  var seconds = 0
  if (restTime > 0) {
    hour = Math.floor(restTime / (3600 * 1000))
    restTime = restTime % (3600 * 1000)
  }

  if (restTime > 0) {
    minutes = Math.floor(restTime / (60 * 1000))
    restTime = restTime % (60 * 1000)
  }

  if (restTime > 0) {
    seconds = Math.floor(restTime / 1000)
  }
  if (day > 0) {
    formatTime += day + m7Language('public.day2')
  }
  if (hour > 0) {
    formatTime += hour + m7Language('public.hours2')
  }
  if (minutes > 0) {
    formatTime += minutes + m7Language('public.minutes2')
  }
  if (seconds > 0) {
    formatTime += seconds + m7Language('public.seconds')
  }
  return formatTime
}

export function getFormatTimeBySecond (second = 0) {
  return [parseInt(second / 60 / 60), parseInt(second / 60 % 60), parseInt(second % 60)].join(':')
      .replace(/\b(\d)\b/g, '0$1')
}
export function timeFormat (value, flag) {
  let now = new Date()
  let today = now.setHours(0, 0, 0, 0)
  let yestoday = new Date(today - 24 * 60 * 60 * 1000).setHours(0, 0, 0, 0)
  let years = now.getFullYear()
  if (value) {
    let dataTimeArr = value.split(' ')
    let day = dataTimeArr[0].split('-')
    day[1] = Number(day[1])
    day[2] = Number(day[2])
    let dayTimeArr = dataTimeArr[1].split(':')
    let dayTime = dayTimeArr[0] + ':' + dayTimeArr[1]
    let valueDate = new Date(value)
    let currentDay = valueDate.setHours(0, 0, 0, 0)
    let currentYear = valueDate.getFullYear()
    let time = ''
    // let day = new Date(value).toLocaleDateString().split('/')
    // let dayTime = new Date(value).toTimeString().substr(0, 5)
    if (today === currentDay) {
      time = timeFormatM7Language('customer.today') + ' ' + dayTime
    } else if (yestoday === currentDay) {
      time = timeFormatM7Language('customer.yesterday') + ' ' + dayTime
    } else if (currentYear === years) {
      if (flag === 'card') {
        time = `${day[1]}${timeFormatM7Language('business.timeLine.month')}${day[2]}${timeFormatM7Language('business.timeLine.day')}`
      } else {
        time = `${day[1]}${timeFormatM7Language('business.timeLine.month')}${day[2]}${timeFormatM7Language('business.timeLine.day')} ${dayTime}`
      }
    } else {
      if (flag === 'card') {
        time = `${day[0].substr(2)}${timeFormatM7Language('business.timeLine.year')}${day[1]}${timeFormatM7Language('business.timeLine.month')}${day[2]}${timeFormatM7Language('business.timeLine.day')}`
      } else {
        time = `${day[0].substr(2)}${timeFormatM7Language('business.timeLine.year')}${day[1]}${timeFormatM7Language('business.timeLine.month')}${day[2]}${timeFormatM7Language('business.timeLine.day')} ${dayTime}`
      }
    }
    return time
  }
}
export function countDay (mount) {
  let today = new Date()
  today.setDate(today.getDate() + mount)
  return today.getFullYear() + '/' + (today.getMonth() + 1) + '/' + today.getDate()
}

export function startWith (str, prefix) {
  return str.indexOf(prefix) === 0
}
export function getAllUseSingleCallLabel (singleLabels, search) {
  if (!singleLabels) {
    return []
  }
  singleLabels = deepClone(singleLabels)
  let useLabel = []
  let searchLabel = []
  for (let i = 0; i < singleLabels.length; i++) {
    if (!singleLabels[i].type) { // 有些脏数据没有type，默认是单标签
      singleLabels[i].type = 'single'
    }
    if (singleLabels[i].type === 'multi') {
      continue
    }
    if (singleLabels[i].enable && singleLabels[i].type === 'single') {
      useLabel.push(singleLabels[i])
      if (search) { // 判断是搜索
        // singleLabels[i].level = 1
        singleLabels[i].name = singleLabels[i].name + '[' + m7Language('call.singleLabel') + ']'
        const obj = {
          value: {'_id': singleLabels[i]._id, 'name': singleLabels[i].name, 'type': singleLabels[i].type},
          label: singleLabels[i].name,
          disabled:singleLabels[i].disabled
        }
        searchLabel.push(obj)
      }
    }
  }
  let obj = {
    singleLabel: useLabel,
    searchSingleLabel: searchLabel
  }
  return obj
}
export function getAllUseMultiCallLabel (multiLabels, singleArr, search) {
  if (!multiLabels) {
    return ''
  }
  multiLabels = deepClone(multiLabels)
  let multiLabelsArr = []
  let searchFirstLabel = []
  for (let i = 0; i < multiLabels.length; i++) {
    if (!multiLabels[i].type) { // 有些脏数据没有type,默认是单标签
      multiLabels[i].type = 'single'
    }
    if (multiLabels[i].type === 'single') { // 若是单标签跳出循环
      continue
    }
    const item = multiLabels[i]
    if (search) {
      let name = item.name + '[' + m7Language('call.multiLabel') + ']'
      item.name = name
    }
    const obj = {
      value: {'_id': item._id, 'name': item.name, 'type': item.type},
      label: item.name,
      disabled:item.disabled
    }
    if (item.child && item.child.length > 0) {
      obj.children = []
      const twoChilds = item.child || []
      for (let j = 0; j < twoChilds.length; j++) {
        const item2 = twoChilds[j]
        const obj2 = {
          value: {'_id': item2._id, 'name': item2.name},
          label: item2.name,
          disabled:item2.disabled
        }
        if (item2.child && item2.child.length > 0) {
          obj2.children = []
          const threeChilds = item2.child || []
          for (let k = 0; k < threeChilds.length; k++) {
            const item3 = threeChilds[k]
            const obj3 = {
              value: {'_id': item3._id, 'name': item3.name},
              label: item3.name,
              disabled:item3.disabled
            }
            if (item3.child && item3.child.length > 0) {
              obj3.children = []
              const fourChilds = item3.child || []
              for (let l = 0; l < fourChilds.length; l++) {
                const item4 = fourChilds[l]
                const obj4 = {
                  value: {'_id': item4._id, 'name': item4.name},
                  label: item4.name,
                  disabled:item4.disabled
                }
                if (item4.child && item4.child.length > 0) {
                  obj4.children = []
                  const fiveChilds = item4.child || []
                  for (let m = 0; m < fiveChilds.length; m++) {
                    const item5 = fiveChilds[m]
                    const obj5 = {
                      value: {'_id': item5._id, 'name': item5.name},
                      label: item5.name,
                      disabled:item5.disabled
                    }
                    if (item5.enable) {
                      obj4.children.push(obj5) // 搜索条件的第四级
                    }
                  }
                }
                if (item4.enable) {
                  if (obj4.children && obj4.children.length <= 0) {
                    delete obj4.children
                  }
                  obj3.children.push(obj4) // 搜索条件的第四级
                }
              }
            }
            if (item3.enable) {
              if (obj3.children && obj3.children.length <= 0) {
                delete obj3.children
              }
              obj2.children.push(obj3) // 搜索条件的第三级
            }
          }
        }
        if (item2.enable) {
          if (obj2.children && obj2.children.length <= 0) {
            delete obj2.children
          }
          obj.children.push(obj2)
        }
      }
    }
    if (item.enable) {
      if (obj.children && obj.children.length <= 0) {
        delete obj.children
      }
      multiLabelsArr.push(obj)
      searchFirstLabel.push(obj) // 搜索条件第一级
    }
  }
  if (singleArr) { // 搜索的时候把单标签也合到一级标签里面
    searchFirstLabel = searchFirstLabel.concat(singleArr)
  }
  let obj = {
    multiLabels: multiLabelsArr,
    searchFirstLabel: searchFirstLabel
  }
  return obj
}
export function getSingleOrMultiLabelNameById (allLables, _id) {
  if (!allLables) {
    return ''
  }
  if (_id) {
    _id = _id.replace(',', '')
  }
  for (let i = 0; i < allLables.length; i++) {
    if (allLables[i]._id === _id) {
      return allLables[i].name || ''
    }
  }
  return ''
}
export function getLabelName (multiLabel, item, labelStr) {
  let childItem = null
  for (let m in item) {
    if (multiLabel.indexOf(item[m]._id) > -1) {
      labelStr += `${item[m].name} >`
      if (item[m].child && item[m].child.length >= 0) {
        childItem = item[m].child
      }
    }
  }
  if (childItem) {
    return getLabelName(multiLabel, childItem, labelStr)
  } else {
    return labelStr
  }
}
export function updateOptions (options, arg) {
  for (let i = 0; i < options.length; i++) {
    const ele = options[i]
    if (ele.state && ele.state === '1') {
      // 过滤停用
      continue
    }
    let obj = {
      label: ele.name,
      value: ele.key,
      children: []
    }
    arg.Arr.push(obj)
    ele.options = ele.options || []
    obj.value = `${ele.key}__${ele.name}`
    ele.options.length > 0 ? updateOptions(ele.options, {Arr: obj.children}) : delete obj.children
    if (obj.children && obj.children.length === 0) {
      delete obj.children
    }
  }
}
export function updateAllOptions (options, arg) {
  for (let i = 0; i < options.length; i++) {
    const ele = options[i]
    let obj = {
      children: [],
      label: ele.name,
      value: ele.key
    }
    arg.Arr.push(obj)
    ele.options = ele.options || []
    obj.value = `${ele.key}__${ele.name}`
    ele.options.length > 0 ? updateAllOptions(ele.options, {Arr: obj.children}) : delete obj.children
  }
}
export function initFinishName (finishOption, finishKeys, str) {
  // 22.9 修复报错问题
  if (finishOption) {
    for (let i = 0; i < finishOption.length; i++) {
      let newStr = str
      if (newStr) {
        newStr += '-->' + finishOption[i].name
        finishKeys[finishOption[i].key] = newStr
      } else {
        finishKeys[finishOption[i].key] = finishOption[i].name
        newStr = finishOption[i].name
      }
      let options = deepClone(finishOption[i].options)
      if (options && options.length > 0) {
        initFinishName(options, finishKeys, newStr)
      }
    }
    return finishKeys
  }
}
export function getCallLabelKeys (finishOption, finishKeys) {
  for (let i = 0; i < finishOption.length; i++) {
    finishKeys[finishOption[i]._id] = finishOption[i].name
    let options = deepClone(finishOption[i].child)
    if (options && options.length > 0) {
      getCallLabelKeys(options, finishKeys)
    }
  }
  return finishKeys
}
/**
 * (flag: noYear) -->  23:23:34
 * (flag: '') -->  2020-10-23 23:23:34
 */
export function getFormatDateTime (date, flag) {
  if (typeof date === 'string') {
    date = new Date(date)
  }
  let year = date.getFullYear()
  let month = date.getMonth()
  let day = date.getDate()
  let hour = date.getHours()
  let minites = date.getMinutes()
  let second = date.getSeconds()
  month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
  day = day > 9 ? day : '0' + day
  hour = hour > 9 ? hour : '0' + hour
  minites = minites > 9 ? minites : '0' + minites
  second = second > 9 ? second : '0' + second
  if (flag === 'noYear') {
    return hour + ':' + minites + ':' + second
  } else if (flag === 'noTime') {
    return year + '-' + month + '-' + day
  } else if (flag === 'monitor') {
    return year + '/' + month + '/' + day + ' ' + hour + ':' + minites + ':' + second
  } else if (flag) {
    return '' + year + month + day + hour + minites + second
  } else {
    return year + '-' + month + '-' + day + ' ' + hour + ':' + minites + ':' + second
  }
}
export function getCurrentDate () {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth()
  let day = date.getDate()
  month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
  day = day > 9 ? day : '0' + day
  return year + '-' + month + '-' + day
}
export function getCurrentDateTime () {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth()
  let day = date.getDate()
  let h = date.getHours()
  let m = date.getMinutes()
  let s = date.getSeconds()
  month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
  day = day > 9 ? day : '0' + day
  h = h > 9 ? h : '0' + h
  m = m > 9 ? m : '0' + m
  s = s > 9 ? s : '0' + s
  return year + '-' + month + '-' + day + ' ' + h + ':' + m + ':' + s
}
/**
 * 计算月份
 * @param startDate
 * 开始日期 2014-4-5
 * @param endDate
 * 结束日期 2015-2-4
 * @return 计算相差月份，必须满足正好一个月才进一
 */
export function getDateMonthSub (startDate, endDate) {
  if (startDate === null || startDate === undefined || startDate === '' || endDate === null || endDate === undefined || endDate === '') {
    return 0
  }
  endDate = new Date(endDate)
  startDate = new Date(startDate)
  let renNumber = 0
  let yearToMonth = (endDate.getFullYear() - startDate.getFullYear()) * 12
  renNumber += yearToMonth
  let startYear = startDate.getFullYear()
  let endYear = endDate.getFullYear()
  let startMon = startDate.getMonth()
  let endMon = endDate.getMonth()
  let startDay = startDate.getDate()
  let endDay = endDate.getDate()
  let monthToMonth = endDate.getMonth() - startDate.getMonth()
  renNumber += monthToMonth
  if (isLastDay(startYear, startMon, startDay) && !isLastDay(endYear, endMon, endDay)) {
    renNumber -= 1
    return renNumber
  } else {
    if (!isLastDay(startYear, startMon, startDay) && !isLastDay(endYear, endMon, endDay)) {
      let startLast = getLastDayAway(startYear, startMon, startDay)
      let endLast = getLastDayAway(endYear, endMon, endDay)
      if (endLast > startLast) {
        renNumber -= 1
        return renNumber
      } else {
        return renNumber
      }
    } else {
      return renNumber
    }
  }
}
/**
 * 判断是否为当年当月的最后一天
 */
export function isLastDay (yearV, monthV, dayV) {
  let newYear = yearV
  let newMonth = monthV + 1
  if (newMonth > 12) {
    newMonth -= 12
    newYear++
  }
  let newDate = new Date(newYear, newMonth, 1)
  let lastDay = (new Date(newDate.getTime() - 1000 * 60 * 60 * 24)).getDate()
  if (lastDay === dayV) {
    return true
  } else {
    return false
  }
}
/**
 * 计算距离月底还有几天
 */
export function getLastDayAway (yearV, monthV, dayV) {
  let newYear = yearV
  let newMonth = monthV + 1
  if (newMonth > 12) {
    newMonth -= 12
    newYear++
  }
  let newDate = new Date(newYear, newMonth, 1)
  let lastDay = (new Date(newDate.getTime() - 1000 * 60 * 60 * 24)).getDate()
  let awayDay = lastDay - dayV
  return awayDay
}
export function getBetweenDays (end, begin) {
  begin = begin || getCurrentDate()
  let diffent = Date.parse(end) - Date.parse(begin)
  return Math.floor(diffent / (1000 * 60 * 60 * 24))
}
export function dateAdd (interval, number, date) {
  switch (interval) {
    case 'y':
      date.setFullYear(date.getFullYear() + number)
      break
    case 'q':
      date.setMonth(date.getMonth() + number * 3)
      break
    case 'M':
      date.setMonth(date.getMonth() + number)
      break
    case 'W':
      date.setDate(date.getDate() + number * 7)
      break
    case 'd':
      date.setDate(date.getDate() + number)
      break
    case 'h':
      date.setHours(date.getHours() + number)
      break
    case 'm':
      date.setMinutes(date.getMinutes() + number)
      break
    case 's':
      date.setSeconds(date.getSeconds() + number)
      break
    default:
      date.setDate(date.getDate() + number)
      break
  }
  return date
}
export function getStrLength (str) {
  let len = 0
  for (let i = 0; i < str.length; i++) {
    let c = str.charCodeAt(i)
    // 单字节加1
    if ((c >= 0x0001 && c <= 0x007e) || (c >= 0xff60 && c <= 0xff9f)) {
      len++
    } else {
      len += 2
    }
  }
  return len
}
export function _getSearchCondition (isAll, arr, sessionId, advItem) { // 等高级搜索调通后要结合高级搜索的搜索条件
  let query = null
  advItem = removeEmptyProperty(advItem) || {} // 清空没有数据的高级搜索条件
  // advItem = advItem || {}
  // 高级搜索条件
  query = advItem
  if (!isAll) {
    let ids = arr
    let _q = null
    if (ids.length > 0) {
      _q = { _id: {$in: ids} }
    } else {
      _q = {_id: 'NA'}
    }
    query = _q
  }
  return query
}
export function removeEmptyProperty (obj) {
  if (!obj) {
    return
  }
  for (let property in obj) {
    let value = obj[property]
    if (!value) {
      delete obj[property]
    }
    if (Array.isArray(value) && value.length === 0) {
      delete obj[property]
    }
  }
  return obj
}
export function isHasFunc (key, user) {
  if (user.type === 'admin' && user.exten === '0000') {
    let reverse = ['func_hide_tel', 'func_nodelete_customer', 'func_forbid_config_formula']
    if (reverse.indexOf(key) !== -1) {
      return false
    } else {
      return true
    }
  }
  let funcIds = user.funcIds
  if (funcIds.indexOf(key) !== -1) {
    return true
  } else {
    return false
  }
}
export function isHasMenu (key, user) {
  let funcIds = user.allFun
  if (user.type === 'admin' && user.exten === '0000') {
    return true
  }
  if (funcIds.indexOf(key) !== -1) {
    return true
  }
  return false
}
export function millsToDate (mills) {
  if (mills < 0) {
    return '00:00:00'
  }
  // 计算出相差天数
  var days = Math.floor(mills / (24 * 3600 * 1000))

  // 计算出小时数
  var leave1 = mills % (24 * 3600 * 1000)    // 计算天数后剩余的毫秒数
  var hours = Math.floor(leave1 / (3600 * 1000))
  // 计算相差分钟数
  var leave2 = leave1 % (3600 * 1000)        // 计算小时数后剩余的毫秒数
  var minutes = Math.floor(leave2 / (60 * 1000))

  // 计算相差秒数
  var leave3 = leave2 % (60 * 1000)      // 计算分钟数后剩余的毫秒数
  var seconds = Math.round(leave3 / 1000)

  var str = ''
  var _hours = ''
  var _minutes = ''
  var _seconds = ''
  if (days !== 0) {
    _hours = days * 24 + hours
  } else {
    _hours = (hours === 0) ? '00' : (hours >= 10 ? hours : ('0' + hours))
  }
  _minutes = (minutes === 0) ? '00' : (minutes >= 10 ? minutes : ('0' + minutes))
  _seconds = (seconds === 0) ? '00' : (seconds >= 10 ? seconds : ('0' + seconds))
  str = _hours + ':' + _minutes + ':' + _seconds
  return str
}
export function checkHideTel (phone, user) {
  if (!phone) return ''
  if (isHasFunc('func_hide_tel', user)) {
    return _encryptPhone(phone)
  } else {
    return phone
  }
}

export function checkEncryptTel (phone, user) {
  if (!phone) return ''
  if (isHasFunc('func_hide_tel', user)) {
    phone = Base64.decode(phone)
  }
  return phone
}
export function _encryptPhone (phone) {
  if (!phone) return ''
  var len = phone.length
  if (len < 6) return phone
  var tel = ''
  var mobile = /1[3,4,5,7,8][0-9]{9}/
  if (mobile.test(phone)) {
    tel = phone.substring(0, 3) + '****' + phone.substring(7)
  } else {
    var p = len / 2
    tel = phone.substring(0, p - 2) + '****' + phone.substring(p + 2)
  }
  return tel
}

// 操作日志的数据进行电话号码隐藏, 拥有隐藏号码权限的时候 加上****隐藏 没有去掉标记$7moorTELStart $7moorTELEnd
export function logDataHideTel (content, user) {
  let reg = /(\$7moorTELStart)/g
  let reg2 = /(\$7moorTELEnd)/g
  if (!reg.exec(content)) return content
  let t = content
    .replace(reg, '###$1')
    .replace(reg2, '$1###')
    .split('###')
    .map(item => {
      if (item.indexOf('$7moorTELStart') > -1) {
        let s = '' // 处理过后的字符串
        let sArry = []
        s = item.replace('$7moorTELStart', '')
          .replace('$7moorTELEnd', '')
        // 含有多个号码是 使用；截取成电话号码 数组
        sArry = s.indexOf(';') ? s.split(';') : sArry.push(s)
        // 有隐藏号码权限则加密 没有就直接返回
        if (isHasFunc('func_hide_tel', user)) {
          s = sArry.reduce((result, value, index) => {
            let str = result + _encryptPhone(value)
            return index + 1 !== sArry.length ? `${str}; ` : str
          }, '')
        }
        item = s
      }
      return item
    }) || []
  return t.join('')
}
export function getDicByIdFor (key, options) {
  options = options || []
  for (let i = 0; i < options.length; i++) {
    var dic = options[i] || {}
    if (dic.key === key) {
      return {'key': key, 'name': dic ? dic.name : ''}
    }
    var opts = dic.options || []
    if (opts.length !== 0) {
      let result = getDicByIdFor(key, opts)
      if (result) {
        return result
      }
    }
  }
}
export function getDicOptionsById (key, options) {
  options = options || []
  for (let i = 0; i < options.length; i++) {
    var dic = options[i] || {}
    if (dic.key === key) {
      return dic.options || []
    }
  }
}
export function getTimeByMs (ctype, ctime) {
  let resultStr
  if (ctype === 'day') {
    resultStr = ctime * 24 * 60 * 60 * 1000
  } else if (ctype === 'hours') {
    resultStr = ctime * 60 * 60 * 1000
  } else if (ctype === 'min') {
    resultStr = ctime * 60 * 1000
  } else if (ctype === 'second') {
    resultStr = ctime * 1000
  }
  return resultStr
}

/**
 * 重置表单
 */
export function resetForm (form) {
  for (let key in form) {
    if (form[key] instanceof Date) {
      form[key] = null
    } else if (typeof form[key] === 'object' && !Array.isArray(form[key])) {
      resetForm(form[key])
    } else if (Array.isArray(form[key])) {
      form[key] = []
    } else {
      form[key] = null
    }
  }
}
export function getDateTime (time, timeForm) {
  if (!time) {
    return ''
  }
  var date = time
  var year = date.getFullYear()
  var month = date.getMonth()
  var day = date.getDate()
  var hour = date.getHours()
  var minites = date.getMinutes()
  var second = date.getSeconds()
  month = month + 1 > 9 ? month + 1 : '0' + (month + 1)
  day = day > 9 ? day : '0' + day
  hour = hour > 9 ? hour : '0' + hour
  minites = minites > 9 ? minites : '0' + minites
  second = second > 9 ? second : '0' + second
  if (timeForm === 'date') {
    return year + '-' + month + '-' + day
  }
  return year + '-' + month + '-' + day + ' ' + hour + ':' + minites + ':' + second
}
export function getChannelLocationName (data) {
  if (data === 'time') {
    return m7Language('call.schedule') // 日程
  } else if (data === 'announcement') {
    return m7Language('call.playVoice') // 播放语音
  } else if (data.toLowerCase() === 'ringing') {
    return m7Language('call.theBell') // 响铃
  } else if (data.toLowerCase() === 'hangup') {
    return m7Language('softPhoneBar.hangup') // 挂机
  } else if (data.toLowerCase() === 'link') {
    return m7Language('call.connected') // 接通
  } else if (data.toLowerCase() === 'queue') {
    return m7Language('public.queues') // 技能组
  } else if (data.toLowerCase() === 'encryptmd5') {
    return m7Language('call.MD5Encryption') // MD5加密
  } else if (data.toLowerCase() === 'voicemail') {
    return m7Language('call.leavingMessage') // 留言
  } else if (data.toLowerCase() === 'ivr') {
    return m7Language('call.buttonMenu') // 按键菜单
  } else if (data.toLowerCase() === 'assignment') {
    return m7Language('call.assignment') // 赋值
  } else if (data.toLowerCase() === 'callurl') {
    return m7Language('call.callUrl') // CallUrl
  } else if (data.toLowerCase() === 'match-blacklist') {
    return m7Language('contactHistoryDisposeDisplay.blackList') // 黑名单
  } else if (data.toLowerCase() === 'route') {
    return m7Language('call.variableRouting') // 按变量路由
  } else if (data.toLowerCase() === 'satisfaction') {
    return m7Language('call.customSatisfaction') // 自定义满意度
  } else if (data.toLowerCase() === 'validate') {
    return m7Language('call.acquisitionInput') // 采集输入
  } else if (data.toLowerCase() === 'room') {
    return m7Language('call.conferenceRoom') // 会议室
  } else if (data.toLowerCase() === 'extensionpeer') {
    return m7Language('call.custom') // 自定义
  } else if (data.toLowerCase() === 'superdialjobnum') {
    return m7Language('call.collectWorkNumber') // 采集工号并拨打
  } else if (data.toLowerCase() === 'menu') {
    return m7Language('cti.TransferIVR') // 转IVR菜单
  } else if (data.toLowerCase() === 'dialjobnum') {
    return m7Language('call.dialNumber') // 拨打工号
  } else if (data.toLowerCase() === 'textannouncement') {
    return m7Language('call.playTextNode') // 播放文本节点
  } else if (data.toLowerCase() === 'date') {
    return m7Language('call.date') // 日期
  } else if (data.toLowerCase() === 'twowaycall') {
    return m7Language('call.twowaycall') // 双向回呼节点
  } else if (data.toLowerCase() === 'asr') {
    return m7Language('call.asr') // 语音识别节点
  } else if (data.toLowerCase() === 'asrend') {
    return m7Language('call.asr') // 语音识别节点
  } else if (data.toLowerCase() === 'ivr-input') {
    return m7Language('call.ivrInput') // 按键
  } else if (data.toLowerCase() === 'agent_hangup') {
    return m7Language('call.unansweredCirculation')
  } else {
    return data
  }
}

export function contains (elems, value) {
  for (let i = 0; i < elems.length; i++) {
    if (elems[i] === value) {
      return true
    }
  }
  return false
}

/**
 * 去掉对象里的空值
 * @param obj
 */
export function trimObjEmptyValue (obj) {
  for (let key in obj) {
    if (!obj[key]) {
      delete obj[key]
    }
  }
}
/**
 * 对html符号进行编码
 * @param str
 * @returns {string|*}
 */
export function escapeHtml (str) {
  str = String(str).replace(/&/gm, '&amp;').replace(/</gm, '&lt;').replace(/>/gm, '&gt;').replace(/'/gm, '&quot;').replace(/'/gm, '&#39;')
  return str
}

/**
 * 解码程html符号
 * @param str
 * @returns {*}
 */
export function unescapeHtml (str) {
  return str.replace(/&amp;/gm, '&').replace(/&lt;/gm, '<').replace(/&gt;/gm, '>').replace(/&quot;/gm, '"').replace(/&#39;/gm, '\'')
}

// 将html片段转化为文字
export function htmlToText (str) {
  if (str) {
    str = str.replace(/(\n)/g, '')
    str = str.replace(/(\t)/g, '')
    str = str.replace(/(\r)/g, '')
    str = str.replace(/<\/?[^>]*>/g, '')
    str = str.replace(/\s*/g, '')
  }
  return str
}

/**
 * 报表部分表头字段timeType检查  时分秒格式 百分比格式
 * */
export function optionTimeTypeCheck (options) {
  let checktimeArray
  let checkpercentArray
  // 采用时分秒格式的列清单
  switch (options.Type) {
    case 'call_report_relay_time':
      checktimeArray = ['IncomingTimeLength', 'IncomingRingingTimeLength']
      break
    case 'call_report_relay_area_city':
      checktimeArray = ['IncomingTimeLength', 'IncomingRingingTimeLength']
      break
    case 'call_report_relay_area':
      checktimeArray = ['IncomingTimeLength', 'IncomingRingingTimeLength']
      break
    case 'call_report_agent':
      checktimeArray = ['LOGIN_TIME_LENGTH', 'CallInTimeLength', 'CallInAverageTimeLength', 'CallOutTimeLength', 'CallOutAverageTimeLength', 'RingingTimeLength', 'HoldTimeLength', 'ConsultTimeLength', 'ThreeWayCallTimeLength', 'IDLE_TIME_LENGTH', 'NormalTransferTimeLength', 'DialTransferTimeLength', 'TransferTimeLength', 'OutgoingWaitingTimeLength', 'IncomingRingingTimeLength', 'MaxCallTimeLength', 'HoldSoftphoneTimeLength', 'BUSY_TIME_LENGTH', 'STATE2_TIME_LENGTH', 'STATE99_TIME_LENGTH']
      break
    case 'call_report_agent_time':
      checktimeArray = ['LOGIN_TIME_LENGTH', 'CallInTimeLength', 'CallInAverageTimeLength', 'CallOutTimeLength', 'CallOutAverageTimeLength', 'RingingTimeLength', 'HoldTimeLength', 'ConsultTimeLength', 'ThreeWayCallTimeLength', 'IDLE_TIME_LENGTH', 'NormalTransferTimeLength', 'DialTransferTimeLength', 'TransferTimeLength', 'OutgoingWaitingTimeLength', 'IncomingRingingTimeLength', 'MaxCallTimeLength', 'HoldSoftphoneTimeLength', 'BUSY_TIME_LENGTH', 'STATE2_TIME_LENGTH', 'STATE99_TIME_LENGTH']
      break
    case 'call_report_callout_time':
      checktimeArray = ['CallTimeLength', 'CallTimeLengthAvg']
      break
    case 'call_report_dialout_area':
      checktimeArray = ['CallTimeLength', 'CallOutAverageTimeLength']
      break
    case 'call_report_dialout_area_city':
      checktimeArray = ['CallTimeLength', 'CallOutAverageTimeLength']
      break
    case 'call_report_queue':
      checktimeArray = ['AcceptAverageCallInTimeLength', 'AcceptAverageQueueTimeLength', 'AcceptMaxQueueTimeLength', 'AcceptMinQueueTimeLength', 'AbandonAverageQueueTimeLength', 'AbandonMaxQueueTimeLength', 'AbandonMinQueueTimeLength']
      break
    case 'call_report_queue_time':
      checktimeArray = ['AcceptAverageCallInTimeLength', 'AcceptAverageQueueTimeLength', 'AcceptMaxQueueTimeLength', 'AcceptMinQueueTimeLength', 'AbandonAverageQueueTimeLength', 'AbandonMaxQueueTimeLength', 'AbandonMinQueueTimeLength']
      break
    case 'im_report_message':
      checktimeArray = ['averageFirstResponseTimeLength', 'averageSessionTimeLength']
      break
    case 'im_report_agent':
      checktimeArray = ['averageFirstResponseTimeLength', 'sessionAverageTimeLength', 'openSessionTotalTime', 'pcOpenSessionTotalTime', 'appOpenSessionTotalTime', 'closeSessionTotalTime', 'customSessionTotalTime', 'sessionTotalTime1', 'sessionTotalTime2', 'sessionTotalTime3', 'sessionTotalTime4', 'sessionTotalTime5']
      break
    case 'im_report_agent_detail':
      checktimeArray = ['averageFirstResponseTimeLength', 'sessionAverageTimeLength', 'openSessionTotalTime', 'pcOpenSessionTotalTime', 'appOpenSessionTotalTime', 'closeSessionTotalTime', 'customSessionTotalTime', 'sessionTotalTime1', 'sessionTotalTime2', 'sessionTotalTime3', 'sessionTotalTime4', 'sessionTotalTime5']
      break
    case 'im_report_agent_response':
      checktimeArray = ['sessionTotalTimeLength', 'responseTotalTimeLength', 'averageResponseTotalTimeLength', 'averageResponseTimeLength', 'maxResponseTimeLength', 'averageFirstResponseTimeLength']
      break
    case 'cc_im_topeer_workload_report':
      checktimeArray = ['sessionAverageTimeLength', 'averageFirstResponseTimeLength']
      break
    case 'cc_im_topeer_wait_report':
      checktimeArray = ['queueAccessAvgTimeLength', 'maxQueueAccessTimeLength', 'queueGiveupAvgTimeLength', 'maxQueueGiveupTimeLength', 'minQueueGiveupTimeLength']
      break
    case 'mail_report_agent':
      checktimeArray = ['sessionAverageTimeLength', 'averageFirstResponseTimeLength', 'mailAutoClaimOpenTimeLength', 'mailAutoClaimCloseTimeLength']
      break
    case 'call_report_dialout_area_city':
      checktimeArray = ['CallTimeLength', 'CallOutAverageTimeLength']
      break
    case 'business_report_analyse':
      checktimeArray = ['finishTimeAvg', 'processTimeAvg', 'waitTimeAvg']
      break
    case 'business_report_agent':
      checktimeArray = ['processTimeAvg', 'waitTimeAvg']
      break
    case 'remoteassist_report_agent':
      checktimeArray = ['avgServerTime', 'serverTime']
      break
  }
  // 带百分比的列清单
  switch (options.Type) {
    case 'call_report_dialout_area_city':
      checkpercentArray = ['CallOutAcceptRate']
      break
    case 'call_report_callout_time':
      checkpercentArray = ['DealingRate']
      break
    case 'call_report_dialout_area':
      checkpercentArray = ['CallOutAcceptRate']
      break
    case 'call_report_queue':
      checkpercentArray = ['AcceptRateNotIn6Leak', 'AcceptRate']
      break
    case 'call_report_queue_time':
      checkpercentArray = ['AcceptRate', 'AcceptRateNotIn6Leak']
      break
    case 'call_report_agent':
      checkpercentArray = ['CallInAcceptRate', 'AgentUtilization']
      break
    case 'call_report_approve_survey':
      checkpercentArray = ['approveSurveyRate']
      break
    case 'im_report_message':
      checkpercentArray = ['sessionRate']
      break
    case 'im_report_agent':
      checkpercentArray = ['sessionCompleteRate', 'inviteSessionRate']
      break
    case 'im_report_csr':
      checkpercentArray = ['appraiseRate', 'agentInviteRate', 'inviteRate', 'appraiseRateOld']
      break
    case 'im_report_channel_csr':
      checkpercentArray = ['appraiseRate']
      break
    case 'business_report_analyse':
      checkpercentArray = ['finishRate', 'createAndFinshRate', 'finishTimeOutCountRate', 'finishWithin24HoursRate', 'finishWithin48HoursRate']
      break
    case 'questionnaire_report_return':
      checkpercentArray = ['sessionCompleteRate']
      break
    case 'im_report_session_seoSource':
      checkpercentArray = ['userConsultRate', 'userLeaveRate']
      break
    case 'im_report_session_area':
      checkpercentArray = ['userConsultRate', 'userLeaveRate']
      break
    case 'im_report_session_seoKeywords':
      checkpercentArray = ['userConsultRate', 'userLeaveRate']
      break
    case 'im_report_session_fromUrl':
      checkpercentArray = ['userConsultRate', 'userLeaveRate']
      break
    case 'mail_report_csr':
      checkpercentArray = ['appraiseRate']
      break
  }
  // 在线客服 - 座席满意度 需要用数和率显示1(0%)   因此减个判断
  options.Config.forEach((item, index) => {
    // if (options.Type !== 'im_report_csr' && options.Type !== 'im_report_channel_csr') {
    // if (options.Type !== 'im_report_channel_csr') {
    if (!item.timeType || item.timeType === 'none') {
      if (checktimeArray && checktimeArray.indexOf(item.name) !== -1) {
        item.timeType = 'hhmmss'
      } else if (checkpercentArray && checkpercentArray.indexOf(item.name) !== -1) {
        item.timeType = 'percent'
      }
    }
  //   } else {
  //     // 在线客服 - 座席满意度 && 渠道满意度 好评率 配置 根据表头顺序判断
  //     if (!item.timeType) {
  //       if (index > 2) {
  //         item.timeType = 'percent'
  //       } else {
  //         item.timeType = 'none'
  //       }
  //     }
  //   }
  })
  return options
}
/**
 * 过滤座席
 * @param {String} module 模块类型
 * @param {Array} agent 座席数组
 * @returns [*]
 */
export function scopeAgents (module, agent) {
  let session = store.state.session
  let agents = agent || []
  let users = []
  if (session.user.type !== 'admin' && session.user.scope[module] !== 'all') {
    let lowUsers = session.user.moduleUsers[module] || []
    for (let i = 0; i < agents.length; i++) {
      for (let j = 0; j < lowUsers.length; j++) {
        if (lowUsers[j] === agents[i]._id) {
          users.push(agents[i])
          break
        }
      }
    }
  } else {
    users = agents
  }
  return users
}

/**
 * 获取到座席的操作系统
 * */
export function getOSInfo () {
  let userAgent = navigator.userAgent
  let isWin = (navigator.platform === 'Win32') || (navigator.platform === 'Windows')
  let isMac = (navigator.platform === 'Mac68K') || (navigator.platform === 'MacPPC') || (navigator.platform === 'Macintosh') || (navigator.platform === 'MacIntel')
  if (isMac) return 'Mac'
  let isUnix = (navigator.platform === 'X11') && !isWin && !isMac
  if (isUnix) return 'Unix'
  let isLinux = (String(navigator.platform).indexOf('Linux') > -1)
  if (isLinux) return 'Linux'
  if (isWin) {
    let winVersion
    winVersion = userAgent.indexOf('Windows NT 5.0') > -1 || userAgent.indexOf('Windows 2000') > -1
    if (winVersion) return 'Windows2000'
    winVersion = userAgent.indexOf('Windows NT 5.1') > -1 || userAgent.indexOf('Windows XP') > -1
    if (winVersion) return 'WindowsXP'
    winVersion = userAgent.indexOf('Windows NT 5.2') > -1 || userAgent.indexOf('Windows 2003') > -1
    if (winVersion) return 'Windows2003'
    winVersion = userAgent.indexOf('Windows NT 6.0') > -1 || userAgent.indexOf('Windows Vista') > -1
    if (winVersion) return 'WindowsVista'
    winVersion = userAgent.indexOf('Windows NT 6.1') > -1 || userAgent.indexOf('Windows 7') > -1
    if (winVersion) return 'Windows7'
    winVersion = userAgent.indexOf('Windows NT 6.2') > -1 || userAgent.indexOf('Windows 8') > -1
    if (winVersion) return 'Windows8'
    winVersion = userAgent.indexOf('Windows NT 6.3') > -1 || userAgent.indexOf('Windows 8.1') > -1
    if (winVersion) return 'Windows8.1'
    winVersion = userAgent.indexOf('Windows NT 6.4') > -1 || userAgent.indexOf('Windows 10') > -1
    if (winVersion) return 'Windows10'
    winVersion = userAgent.indexOf('Windows NT 10.0') > -1 || userAgent.indexOf('Windows 10') > -1
    if (winVersion) return 'Windows10'
  }
  return m7Language('请将未知国际化')
}/**
 * 通话配置搜索
 * @param {object} data 要搜索的对象
 * @param {string} search 搜索条件
 * @param {array} mapKey 匹配的key值
 * @returns [*]
 */
export function ivrSearch (data, search, mapKeys) {
  let searchResult = []
  if (data) {
    let node = null
    let key = null
    let searchResultMap = {}
    for (let i = 0; i < data.length; i++) {
      node = data[i]
      for (let j = 0; j < mapKeys.length; j++) {
        key = mapKeys[j]
        if (node[key] && node[key].indexOf(search) > -1) {
          if (!searchResultMap[node._id]) {
            searchResultMap[node._id] = node
            searchResult.push(node)
          }
        }
      }
    }
    searchResultMap = null
  }
  return searchResult
}
/*
* 排序类型转换
* */
export function sortConvert (dataValue, dataType) {
  let value = dataValue
  switch (dataType) {
    case 'int':
      return parseInt(value)
    case 'float':
      return parseFloat(value)
    case 'date':
      return new Date(Date.parse(value))
    case 'intAndString':
      return parseInt(value.substring(0, value.indexOf('(')))
    default:
      return value.toString()
  }
}
/**
 * @obj 判断是否为空对象
 * */
export function isEmptyObj (obj) {
  for (let key in obj) {
    return false
  }
  return true
}
export function innerHtmlChannelColor (node) {
  let channelGlobalSet = m7dicMap.getCache('channelGlobalSet')
  let color = channelGlobalSet.backgroundColor || ''
  let pane = document.getElementById('label_style_7moor')
  if (pane && pane.childNodes && pane.childNodes.length > 0) {
    pane.removeChild(pane.childNodes[0])
  }
  let sessionColor = document.createElement('style')
  color = color.replace(/#/g, '')
  if (sessionColor) {
    let style = 'label7moor,label7moor a{color:#' + color + '!important}'
    sessionColor.innerHTML = style
  }
  pane.appendChild(sessionColor)
}
/*
** randomWord 产生任意长度随机字母数字组合
** randomFlag 是否任意长度 min-任意长度最小位[固定位数] max-任意长度最大位
*/
export function randomWord (randomFlag, min, max) {
  let str = ''
  let range = min
  let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
  // 随机产生
  if (randomFlag) {
    range = Math.round(Math.random() * (max - min)) + min
  }
  for (var i = 0; i < range; i++) {
    let pos = Math.round(Math.random() * (arr.length - 1))
    str += arr[pos]
  }
  return str
}

export function searchDataReturn (value) {
  let nowTime = new Date()
  let mtDate = nowTime.getTime()
  let startTime = ''
  let endTime = getFormatDateTime(new Date()).split(' ')[0] + ' 23:59:59'
  if (value === 'week') {
    // 近一周
    startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 6)).split(' ')[0] + ' 00:00:00'
  } else if (value === 'today') {
    // 今天
    startTime = getFormatDateTime(new Date(mtDate)).split(' ')[0] + ' 00:00:00'
  } else if (value === 'yesterday') {
    // 昨天
    startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 00:00:00'
    endTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24)).split(' ')[0] + ' 23:59:59'
  } else if (value === 'month') {
    // 近一月
    startTime = getFormatDateTime(new Date(mtDate - 3600 * 1000 * 24 * 29)).split(' ')[0] + ' 00:00:00'
  } else {
    endTime = ''
  }
  let searchQuery = {
    createTime$begin: startTime,
    createTime$end: endTime
  }
  return searchQuery
}
// 更新vue数据
export function update (target, data, vue) {
  let self = vue || this
  for (let key in target) {
    if (!(key in data)) {
      self.$delete(target, key)
    }
  }
  for (const key in data) {
    if (key in target) {
      target[key] = data[key]
    } else {
      self.$set(target, key, data[key])
    }
  }
}
//      假分页处理方法
// 参数依次为：当前页  全部列表  页容量默认为10可以不传
export function handleFakePage (curPage, _array, pageSize = 10) {
  let arr = []
  for (let i = (curPage - 1) * pageSize; i < curPage * pageSize && i < _array.length; i++) {
    arr.push(_array[i])
  }
  return arr
}
//      模糊搜索处理方法
// 参数依次为：搜索内容  搜索的key值  被搜索数组
export function filterAct (val, type, arrList) {
  // 如果搜索条件为空 返回全部
  if (!val || !type) {
    return arrList
  }
  let arr = []
  arr = arrList.filter(item => {
    if (item[type].indexOf(val) >= 0) {
      return item
    }
  })
  return arr
}
//     校验数组是否有重复数据
export function isRepeat (arr) {
  let hash = {}
  for (let i in arr) {
    if (hash[arr[i]]) {
      return true
    }
    // 不存在该元素，则赋值为true，可以赋任意值，相应的修改if判断条件即可
    hash[arr[i]] = true
  }
  return false
}
// 删除option里面的停用项
export function deleteDisabledOption (option) {
  // let options = option.options || []
  if (option.options && option.options.length) {
    option.options = option.options.filter((item) => {
      // state为1 则停用该项
      if (item.state !== '1') {
        deleteDisabledOption(item)
        return true
      }
    })
  }
}
export function replaceHtmlToStr (str) { // 去除字符串中的html
  let reg1 = new RegExp('<[^<]*>', 'gi')
  str = str.replace(reg1, '')
  let reg2 = new RegExp('</', 'gi')
  str = str.replace(reg2, '')
  return str
}
// 处理表头国际化
export function dealReportRes (res) {
  let config = []
  if (res.tableHeader && res.tableHeader.Config) {
    config = res.tableHeader.Config
  } else if (res.Config) {
    config = res.Config
  }
  config.forEach((item) => {
    item.displayname = m7Language('reportChineseKey.' + item.displayname, null, true) || item.displayname
  })
  return res
}
// 上传文件限制类型
export const UPLOAD_LIMITED_TYPE = ['js', 'jsp', 'html', 'php', 'asp', 'aspx', 'jspx', 'exe', 'sh', 'py', 'vbs', 'xml', 'htm']

export function encrypt(secretKey, plaintText) {
  var plaintText = plaintText
  var options = {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
  }
  var key = CryptoJS.enc.Utf8.parse(secretKey)
  var encryptedData = CryptoJS.AES.encrypt(plaintText, key, options)
  var encryptedBase64Str = encryptedData.toString().replace(/\//g, "_")
  encryptedBase64Str = encryptedBase64Str.replace(/\+/g,"-")
  return encryptedBase64Str
}

export function decrypt(secretKey, encryptedBase64Str) {
  var vals = encryptedBase64Str.replace(/\-/g, '+').replace(/_/g, '/');
  var options = {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
  };
  var key = CryptoJS.enc.Utf8.parse(secretKey);
  var decryptedData = CryptoJS.AES.decrypt(vals, key, options);
  var decryptedStr = CryptoJS.enc.Utf8.stringify(decryptedData);
  return decryptedStr
}
export function aesEncrypt (data) {
  let key = CryptoJS.enc.Utf8.parse('7moor1234567891234567890') // 十六位十六进制数作为密钥
  let iv = CryptoJS.enc.Utf8.parse('88f875ce0e9b4884') // 十六位十六进制数作为密钥偏移量
  let options = {
    iv: iv,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  }
  var encrypted = CryptoJS.AES.encrypt(data, key, options)
  var enHex = encrypted.ciphertext.toString()
  return enHex
}

export function getAesEncrypt (key, iv, content) { // 敏感数据加密 - aes加密方式（AES/CBC/PKCS5Padding）
  key = CryptoJS.enc.Utf8.parse(key)
  let srcs = CryptoJS.enc.Utf8.parse(content)
  // 加密模式为CBC，补码方式为PKCS5Padding（也就是PKCS7）
  let option = { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
  if (iv) { // iv如果有传递
    iv = CryptoJS.enc.Utf8.parse(iv)
    option.iv = iv
  }
  let encrypted = CryptoJS.AES.encrypt(srcs, key, option)
  let result = encrypted.ciphertext.toString()
  console.log(result, '==========')
  //返回base64
  return result.toLocaleUpperCase()
}
